const http = require('http');
// console.log(http);
const url = require('url');

const { render } = require("../tool/read");
const { search, searchOne } = require('../tool/db');

// 创建本地服务器来从其接收数据
var server = http.createServer(async function (req, res) { // 接收到请求时执行的回调函数
    // req  => request 
    // res  => response
    // console.log(111111);
    // console.log(req);

    if (req.url != "/favicon.ico") {  //排除网页标题图标
        console.log("接收到请求!!!");

        var obj = url.parse(req.url, true);
        console.log(obj);

        req.query = obj.query;

        var URL = obj.pathname;
        console.log(URL);

        /*  server.get = function(path,fn){
             fn(req,res)
         } */

        if (URL == "/") {
            var result = await render("./index.html");
            res.write(result);
        } else if (URL == "/login") {
            var result = await render("./html/login.html");
            res.write(result);
        } else if (URL == "/reg") {
            var result = await render("./html/register.html");
            res.write(result);
        } else if (URL == "/list") {  // 路由 => 接口
            res.writeHead(200, { "Content-Type": "text/json;charset=utf-8" });
            var sql = "select * from `grade`"
            var data = await search(sql);
            res.write(JSON.stringify(data))
        } else if (URL == "/searchGradeById") {  // 路由 => 接口
            res.writeHead(200, { "Content-Type": "text/json;charset=utf-8" });
            var id = req.query.id;
            var msg = {};
            if (id) {
                var sql = `select * from grade where id = ${id}`;
                var data = await searchOne(sql);
                if (data) {
                    msg.status = true;
                    msg.data = data;
                    msg.message = "Ok!";
                } else {
                    msg.status = false;
                    msg.message = "暂无数据";
                }
            } else {
                msg.status = false;
                msg.message = "请传入完整参数";

            }
            res.write(JSON.stringify(msg))
        } else {
            try {
                var result = await render(URL);
                res.write(result);
            } catch (err) {
                console.log(err);
                var result = await render("./error/404.html");
                res.write(result);
            }
        }


    }

    res.end();

})
// console.log(server);

server.listen(3000, function () { // 服务启动时执行的回调函数
    console.log("服务已启动:localhost:3000");
})